package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"job-manager/cache"
	"job-manager/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Job{}).Count(&count)

	var job []models.Job

	redis_key := "list_job" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Order("ID desc").Offset(offset).Limit(size).Find(&job)
		jsonData, _ := json.Marshal(job)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &job)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"job":   job,
		},
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var job models.Job

	redis_key := "detail_job" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id = ?", id).First(&job)
		jsonData, _ := json.Marshal(job)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &job)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": job,
	})
	return
}
func Collection(c *gin.Context) {
	jobId, _ := strconv.Atoi(c.Query("job_id"))
	var collection models.Collection
	err := models.DB.Where("job_id = ?", jobId).First(&collection).Error
	if err == nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能重复收藏",
		})
		return
	}

	collection = models.Collection{
		JobID: jobId,
	}
	err = models.DB.Create(&collection).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏添加失败",
		})
		return
	}

	var job models.Job
	err = models.DB.Where("id = ?", jobId).First(&job).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不存在",
		})
		return
	}

	job.CollectionCount++
	err = models.DB.Save(&job).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
